from fastapi import APIRouter, Depends, HTTPException, Request, Form, Cookie, Query
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session
from database import get_db
from models import User
from utils import get_password_hash, update_user_settings, delete_user_sessions
from core.logger import app_logger as logger
from templates import templates
from typing import Optional
from datetime import datetime
from utils import validate_session
router = APIRouter()

# 检查用户是否为管理员
def is_admin(request: Request):
    SessionId = request.cookies.get("SessionId")
    UserName = request.cookies.get("UserName")
    Role = request.cookies.get("Role")
    
    if not SessionId or not UserName or not Role or Role != "admin":
        logger.info(f"{UserName}不是管理员，拒绝访问。")
        return False
    logger.info(f"确认{UserName}是管理员，允许访问。")
    return True

# 用户管理主页面
@router.get("/adminmanage", response_class=HTMLResponse)
async def user_management_page(
    request: Request,
    SessionId: Optional[str] = Cookie(None),
    UserName: Optional[str] = Cookie(None),
    db: Session = Depends(get_db),
    page: int = Query(1, ge=1),
    search: str = Query(None),
    error: str = Query(None)
):
    if not SessionId or not UserName or not validate_session(SessionId, UserName):
        return RedirectResponse(url="/")
    # 权限检查（仅管理员可访问）
    if not is_admin(request):
        return RedirectResponse(url="/?error=权限不足")
    
    # 分页参数
    per_page = 10
    offset = (page - 1) * per_page
    
    # 构建查询 - 只查询未删除的用户(DeadTime为NULL)
    query = db.query(User).filter(User.DeadTime == None)
    
    # 搜索功能
    if search:
        query = query.filter(
            (User.UserName.ilike(f"%{search}%")) |
            (User.RealName.ilike(f"%{search}%")) |
            (User.Contact.ilike(f"%{search}%"))
        )
    
    # 获取用户总数
    total_users = query.count()
    
    # 获取当前页用户
    users = query.order_by(User.UserId.asc()).offset(offset).limit(per_page).all()
    
    # 计算总页数
    total_pages = (total_users + per_page - 1) // per_page
    
    return templates.TemplateResponse("adminmanage.html", {
        "request": request,
        "users": users,
        "current_page": page,
        "total_pages": total_pages,
        "search": search,
        "error": error
    })
# 添加用户
@router.post("/add_user")
async def add_user(
    request: Request,
    UserName: str = Form(...),
    Password: str = Form(...),
    Role: str = Form(...),
    RealName: str = Form(...),
    Contact: str = Form(...),
    db: Session = Depends(get_db)
):
    # 权限检查（仅管理员可访问）
    if not is_admin(request):
        return RedirectResponse(url="/?error=权限不足")
    
    # 角色验证
    if Role not in ["user", "admin", "deployer"]:
        return RedirectResponse(url="/adminmanage?error=无效的用户角色", status_code=303)
    
    # 检查用户名长度
    if len(UserName) > 10:
        return RedirectResponse(url="/adminmanage?error=用户名不能超过10位", status_code=303)
    
    # 检查联系方式长度
    if Contact and len(Contact) > 15:
        return RedirectResponse(url="/adminmanage?error=联系方式不能超过15位", status_code=303)
    
    # 检查用户名是否已被使用（无论是否删除）
    existing_user = db.query(User).filter(
        User.UserName == UserName
    ).first()
    
    if existing_user:
        return RedirectResponse(url="/adminmanage?error=用户名已被使用", status_code=303)
    
    # 密码长度验证
    if len(Password) < 6:
        return RedirectResponse(url="/adminmanage?error=密码长度至少为6位", status_code=303)
    
    # 创建新用户
    new_user = User(
        UserName=UserName,
        Password=get_password_hash(Password),
        Role=Role,
        RealName=RealName,
        Contact=Contact
    )
    
    try:
        db.add(new_user)
        db.commit()
        
        # 初始化用户设置
        update_user_settings(UserName, {
            "theme": "light",
            "notifications": True,
            "language": "zh",
            "font_size": "medium"
        })
        
        return RedirectResponse(url="/adminmanage?success=用户添加成功", status_code=303)
    except Exception as e:
        db.rollback()
        logger.error(f"添加用户失败: {str(e)}")
        return RedirectResponse(url="/adminmanage?error=添加用户失败", status_code=303)

# 编辑用户页面
@router.get("/editadmin/{UserId}", response_class=HTMLResponse)
async def edit_user_page(
    request: Request,
    UserId: int,
    db: Session = Depends(get_db),
    error: str = Query(None)
):
    # 权限检查（仅管理员可访问）
    if not is_admin(request):
        return RedirectResponse(url="/?error=权限不足")
    
    user = db.query(User).filter(User.UserId == UserId).first()
    if not user:
        return RedirectResponse(url="/adminmanage?error=用户不存在", status_code=303)
    
    return templates.TemplateResponse("editadmin.html", {
        "request": request,
        "user": user,
        "error": error
    })

# 更新用户信息
@router.post("/update_user/{UserId}")
async def update_user(
    request: Request,
    UserId: int,
    UserName: str = Form(...),
    Role: str = Form(...),
    RealName: str = Form(...),
    Contact: str = Form(...),
    NewPassword: str = Form(None),  # 可选字段
    db: Session = Depends(get_db)
):
    # 权限检查（仅管理员可访问）
    if not is_admin(request):
        return RedirectResponse(url="/?error=权限不足")
    
    user = db.query(User).filter(User.UserId == UserId).first()
    if not user:
        return RedirectResponse(url="/adminmanage?error=用户不存在", status_code=303)
    
    # 角色验证
    if Role not in ["user", "admin", "deployer"]:
        return RedirectResponse(url=f"/editadmin/{UserId}?error=无效的用户角色", status_code=303)
    
    # 检查用户名长度
    if len(UserName) > 10:
        return RedirectResponse(url=f"/editadmin/{UserId}?error=用户名不能超过10位", status_code=303)
    
    # 检查联系方式长度
    if Contact and len(Contact) > 15:
        return RedirectResponse(url=f"/editadmin/{UserId}?error=联系方式不能超过15位", status_code=303)
    
    # 检查用户名是否已被其他用户使用（无论是否删除）
    existing_user = db.query(User).filter(
        User.UserName == UserName,
        User.UserId != UserId  # 排除当前用户
    ).first()
    
    if existing_user:
        return RedirectResponse(url=f"/editadmin/{UserId}?error=用户名已被使用", status_code=303)
    
    # 更新字段
    user.UserName = UserName
    user.Role = Role
    user.RealName = RealName
    user.Contact = Contact
    
    # 如果提供了新密码，则更新
    if NewPassword:
        if len(NewPassword) < 6:
            return RedirectResponse(url=f"/editadmin/{UserId}?error=密码长度至少为6位", status_code=303)
        user.Password = get_password_hash(NewPassword)
    
    try:
        db.commit()
        return RedirectResponse(url="/adminmanage?success=用户信息更新成功", status_code=303)
    except Exception as e:
        db.rollback()
        logger.error(f"更新用户失败: {str(e)}")
        return RedirectResponse(url=f"/editadmin/{UserId}?error=更新用户失败", status_code=303)

# 删除用户
@router.get("/delete_user/{UserId}")
async def delete_user(
    request: Request,
    UserId: int,
    db: Session = Depends(get_db)
):
    # 权限检查（仅管理员可访问）
    if not is_admin(request):
        return RedirectResponse(url="/?error=权限不足")
    
    current_user = request.cookies.get("UserName")
    if str(UserId) == request.cookies.get("UserId"):
        return RedirectResponse(url="/adminmanage?error=不能删除当前登录的用户", status_code=303)
    
    # 查找未删除的用户（Deadtime为NULL）
    user = db.query(User).filter(
        User.UserId == UserId,
        User.DeadTime == None  # 只处理未删除的用户
    ).first()
    
    if not user:
        return RedirectResponse(url="/adminmanage?error=用户不存在", status_code=303)
    
    # 检查是否是管理员且是最后一个管理员
    if user.Role == "admin":
        # 查询系统中未删除的管理员数量
        admin_count = db.query(User).filter(
            User.Role == "admin",
            User.DeadTime == None
        ).count()
        
        # 如果只剩下一个管理员（即当前要删除的这个），则阻止删除
        if admin_count == 1:
            return RedirectResponse(
                url="/adminmanage?error=无法删除：系统中至少需要保留一个管理员",
                status_code=303
            )
    
    try:
        # 删除用户的所有会话
        delete_user_sessions(user.UserName)
        
        # 逻辑删除：更新DeadTime为当前时间
        user.DeadTime = datetime.now()
        db.commit()
        
        return RedirectResponse(url="/adminmanage?success=用户删除成功", status_code=303)
    except Exception as e:
        db.rollback()
        logger.error(f"删除用户失败: {str(e)}")
        return RedirectResponse(url="/adminmanage?error=删除用户失败", status_code=303)